#  订单控制层
#  提交购物出商品  ----> 查验库存 ----> 扣减库存------> 生成订单 ----> 返回订单id
#  跳转支付页面 ------> 显示用订单详情 ------>支付 -----> 改变订单状态 -----> 交易完成 -----> 商品出库 -----> 物流


# 前端提交 cart 实体类对象数组
import json

from django.http import HttpResponse

from entity.common.response import ResponseData, ResponseStatus
from orderApp.service.addressService import AddressService
from orderApp.service.orderService import OrderService
from utils.transfer import transferToJson

orderService = OrderService()
addressService = AddressService()


def postCartGoods(request):
    if request.method == 'POST':
        try:
            user = json.loads(request.session['user'])
            address = json.loads(request.body)
            order = orderService.createOrder(user['id'])
            address['user_id'] = user['id']
            address['order_id'] = order.order_id
            addressService.add(address)
            # 从购物车中删除商品
            orderService.deleteCart(user['id'])
            response = ResponseData(success=True, responseCode=ResponseStatus.SUCESS, message="下单成功",
                                    data={"id": order.order_id})
        except Exception as err:
            print(err)
            response = ResponseData(success=False,responseCode=ResponseStatus.OPERATION_FAIL,message="服务异常")
    else:
        response = ResponseData(success=False,responseCode=ResponseStatus.METHOD_ERROR,message="请求方法错误")
    return HttpResponse(content=transferToJson(response), content_type=ResponseData.JSON_CONTENT_TYPE)

# 暂时无法使用！！！ 和前端页面冲突，矛盾
# 生成订单后返回订单号，前端根据订单号，请求订单信息，跳转到结算页面
def getOrder(request):
    response = ResponseData(success=False,responseCode=ResponseStatus.RESPONSE_FAIL,message="",data='')
    if request.method == 'POST':
        orderId = json.loads(request.body)['order_id']
        order = orderService.getOrderDetailById(orderId)
        order['create_time'] = (str)(order['create_time'])
        order['total_price'] = (str)(order['total_price'])
        response = ResponseData(success=False,responseCode=ResponseStatus.SUCESS,message="",data=order)
    return HttpResponse(content=transferToJson(response), content_type=ResponseData.JSON_CONTENT_TYPE)

# 更改订单状态 ,这里模拟支付更改状态，由前端将状态传入，后期整合微信支付，再做修改
# 0 ---> 未支付  默认状态
# 1 ---> 支付
# 2 ---> 取消
def payOrder(request):
    isSuccess = False
    if request.method == 'POST':
        body =  json.loads(request.body)
        orderId = body['order_id']
        status = body['status']
        userId = json.loads(request.session['user'])['id']
        isSuccess=orderService.changeOrderStatus(orderId=orderId,userId=userId,status=status)
    response = ResponseData(success=isSuccess,responseCode=ResponseStatus.COMPLETE_RESPONSE,message="",data=[])
    return HttpResponse(content=transferToJson(response),content_type=ResponseData.JSON_CONTENT_TYPE)
